﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Data;
using System.Text;
/// <summary>
///BaseDataPage 的摘要说明
/// </summary>
public class BaseDataPage: Page
{
    public MyDbHelper mydb = new MyDbHelper();
    public DbHelper db = new DbHelper();
    public bool IsAdd;
    private string mid = "";

	public BaseDataPage()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}

    protected virtual void Page_Load(object sender, EventArgs e)
    {
        if (Session["userName"] == null)
        {
            ShowMessage(Response,"登录信息已超时，按F5请重新登录！");
        }
        mid = Request.Params["mid"];
        //if (string.IsNullOrEmpty(mid))
        //{
        //    Response.Write("<script type='text/javascript'>alert('地址错误，无法访问！');window.location.href = '../welcome.html';</script>");
        //    return;
        //}
        if (!IsPostBack)
        {
            if (!string.IsNullOrEmpty(mid))
            {
                CheckModulesRights(mid, "M_Browse", "您没有权限操作此模块，请联系管理员！", "../welcome.html");
            }    
        }

    }

    protected bool CheckModulesRights(string mid, string action, string msg, string url)
    {
        string isBrowse = mydb.DM_GetExecuteScalarObj("select " + action + " from sys_modulerights where mid=" + mid
            + " and userid=" + Session["UserID"]).ToString();
        if (string.IsNullOrEmpty(isBrowse))
        {
            Response.Write("<script type='text/javascript'>alert('" + msg + "');window.location.href = '" + url + "';</script>");
            return false;
        } if (isBrowse.ToLower() == "-1")
        {
            Response.Write("<script type='text/javascript'>alert('" + msg + "');window.location.href = '" + url + "';</script>");
            return false;
        }
        if (isBrowse.ToLower() == "false")
        {
            Response.Write("<script type='text/javascript'>alert('" + msg + "');window.location.href = '" + url + "';</script>");
            return false;
        }
        InsertActionLog(Session["UserID"].ToString(),mid,"浏览",DateTime.Now.ToString());
        return true;
    }

    public void InsertActionLog(string userid,string mid,string action,string datetime)
    {
        string sql = @"insert into sys_useractionlog(userid,mid,acname,acdatetime)
                        values("+userid+","+mid+",'"+action+"','"+datetime+"')";
        mydb.DM_ExecuteNonQuery(sql);
    }


    public void ShowMessage(HttpResponse rsp,string msg)
    {
        rsp.Write("<script type='text/javascript'>alert('" + msg + "')</script>");
    }

    public  DataSet BinUserList(string param)
    {
        string str = "";
        if (param != "")
        {
            str += " and usercode like '%" + param + "%' or username like '%" + param + "%'";
        }
        return mydb.DM_GetDateSet("select * from sys_loginuser where 1=1" + str);
    }


    public void IniModleTree(TreeView tv)
    {
        tv.Nodes.Clear();
        string sql = "select * from sys_modules where parentid = 0 order by mindx";
        DataSet ds = mydb.DM_GetDateSet(sql);
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                TreeNode node = new TreeNode();
                node.Text = "[" + dr["mindx"].ToString() + "]" + dr["modulename"].ToString();
                node.Value = dr["mid"].ToString();
                tv.Nodes.Add(node);
                AddChildNode(node, dr["mid"].ToString());
            }
        }
        tv.ExpandAll();
    }
    private void AddChildNode(TreeNode node, string parentid)
    {
        string sql = "select * from sys_modules where parentid = " + parentid + " order by mindx";
        DataSet ds = mydb.DM_GetDateSet(sql);
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                TreeNode childNode = new TreeNode();
                childNode.Text = "[" + dr["mindx"].ToString() + "]" + dr["modulename"].ToString();
                childNode.Value = dr["mid"].ToString();
                node.ChildNodes.Add(childNode);
                AddChildNode(childNode, dr["mid"].ToString());
            }
        }
    }
    public string CheckString(string str)
    {
        string returnStr = "";
        if (str.IndexOf("'") != -1) //判断字符串是否含有单引号
        {
            returnStr = str.Replace("'", "''");
            str = returnStr;
        }
        return str;
    }
    public string SplitStr(string str)
    {
        string val = "";
        if (str.Trim() != "")
        {
            val += "(";
            string[] list = str.Split(',');
            foreach (string s in list)
            {
                val += "''" + s + "'',";
            }
            val = val.TrimEnd(',');
            val += ")";
        }
        return val;
    }
    public void GetDataToJsonBySql(HttpResponse rep, string sql)
    {
        string sbr = "";
        DataSet ds = mydb.DM_GetDateSet(sql);
        if (ds != null)
        {
            if (ds.Tables[0].Rows.Count == 0)
            {
                sbr = "{\"status\":\"1\",\"msg\":\"没有数据！\"}";
            }
            else
            {
                sbr = DataSetToJson(ds);
            }
        }
        else
        {
            sbr = "{\"status\":\"0\",\"msg\":\"出现错误！\"}";
        }
        rep.Write(sbr);
        rep.End();
    }
    public void GetDataToJsonBySql2(HttpResponse rep, string sql)
    {
        string sbr = "";
        DataSet ds = db.DM_GetDateSet(sql);
        if (ds != null)
        {
            if (ds.Tables[0].Rows.Count == 0)
            {
                sbr = "{\"status\":\"1\",\"msg\":\"没有数据！\"}";
            }
            else
            {
                sbr = DataSetToJson(ds);
            }
        }
        else
        {
            sbr = "{\"status\":\"0\",\"msg\":\"出现错误！\"}";
        }
        rep.Write(sbr);
        rep.End();
    }
    /// <summary>
    /// 将DataSet转化成JSON数据
    /// </summary>
    /// <param name="ds"></param>
    /// <returns></returns>
    public static string DataSetToJson(DataSet ds)
    {
        string json = string.Empty;
        try
        {
            if (ds.Tables.Count == 0)
                throw new Exception("DataSet中Tables为0");
            //json = "{";
            for (int i = 0; i < ds.Tables.Count; i++)
            {
                json += "[";
                for (int j = 0; j < ds.Tables[i].Rows.Count; j++)
                {
                    json += "{";
                    for (int k = 0; k < ds.Tables[i].Columns.Count; k++)
                    {
                        json += "\""+ds.Tables[i].Columns[k].ColumnName + "\":\"" + ds.Tables[i].Rows[j][k].ToString() + "\"";
                        if (k != ds.Tables[i].Columns.Count - 1)
                            json += ",";
                    }
                    json += "}";
                    if (j != ds.Tables[i].Rows.Count - 1)
                        json += ",";
                }
                json += "]";
                if (i != ds.Tables.Count - 1)
                    json += ",";


            }
            //json += "}";
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        return json;
    }
    #region DataSet转换成Json格式
    /// <summary>    
    /// DataSet转换成Json格式    
    /// </summary>    
    /// <param name="ds">DataSet</param>    
    /// <returns></returns>    
    public static string Dataset2Json(DataSet ds)
    {
        StringBuilder json = new StringBuilder();

        foreach (DataTable dt in ds.Tables)
        {
            json.Append("{\"");
            json.Append(dt.TableName);
            json.Append("\":");
            json.Append(DataTable2Json(dt));
            json.Append("}");
        }
        return json.ToString();
    }
    #endregion   
    #region dataTable转换成Json格式
    /// <summary>    
    /// dataTable转换成Json格式    
    /// </summary>    
    /// <param name="dt"></param>    
    /// <returns></returns>    
    public static string DataTable2Json(DataTable dt)
    {
        StringBuilder jsonBuilder = new StringBuilder();
        jsonBuilder.Append("{\"");
        jsonBuilder.Append(dt.TableName.ToString());
        jsonBuilder.Append("\":[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Columns[j].ColumnName);
                jsonBuilder.Append("\":\"");
                jsonBuilder.Append(dt.Rows[i][j].ToString());
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");
        jsonBuilder.Append("}");
        return jsonBuilder.ToString();
    }
    #endregion

    private string dsToJson(DataSet ds)
    {
        System.Text.StringBuilder str = new System.Text.StringBuilder("[");
        for (int o = 0; o < ds.Tables.Count; o++)
        {
            str.Append("{");
            str.Append(string.Format("\"{0}\":[", ds.Tables[o].TableName));

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                str.Append("{");
                for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                {
                    str.Append(string.Format("\"{0}\":\"{1}\",", ds.Tables[0].Columns[j].ColumnName, ds.Tables[0].Rows[i][j].ToString()));
                }
                str.Remove(str.Length - 1, 1);
                str.Append("},");
            }
            str.Remove(str.Length - 1, 1);
            str.Append("]},");
        }
        str.Remove(str.Length - 1, 1);
        str.Append("]");
        return str.ToString();
    }
}